/**
 * 每小时获取一次比特币价格
 */

const moment = require('moment')
const config = require('../config/index')
const log4js = require('log4js')
const schedule = require('node-schedule')
const request = require('request-promise')
const Redis = require('ioredis')
const redis = new Redis(config.redis)

// 配置log4js
log4js.configure(config.log4js)
const logger = log4js.getLogger('比特币准点报价')

let url = 'https://api.huobipro.com/market/history/kline'

async function getPrice () {
  try {
    let res = await request({
      url: url,
      method: 'GET',
      qs: {
        period: '1day',
        size: 1,
        symbol: 'btcusdt'
      },
      json: true
    })
    console.log(res)
    if (res.status === 'ok') {
      let kline = res.data[0]
      let {open, close, high, low} = kline
      return {
        type: 3,
        symbol: 'BTC/USDT',
        source: '火币Pro',
        time: moment().utcOffset(8).format('YYYY-MM-DD HH:mm:ss'),
        content: `  最新价格:$${close}\n今日开盘价:$${open}\n今日最高价:$${high}\n今日最低价:$${low}`
      }
    } else {
      throw new Error('获取比特币价格失败')
    }
  } catch (e) {
    logger.error(e.message)
    return null
  }

}

/**
 * 每4秒执行一次查询
 */
schedule.scheduleJob('0 0 */1 * * *', async () => {
  let news = await getPrice()
  news && console.log(news)
  news && redis.publish('news', JSON.stringify(news))
})
